<template>
  <div class="upload-file">
    <el-upload
      multiple
      :action="uploadFileUrl"
      http-request=""
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      :data="{ type: uploadType }"
      :auto-upload="autoUpload"
      class="upload-file-uploader"
      ref="fileUpload"
    >
      <!-- 上传按钮 -->
      <el-button type="primary">选取文件</el-button>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <!-- <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template> -->
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
      </template>
      的文件
    </div>
    <!-- 文件列表 -->
    <transition-group
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul"
    >
      <li
        :key="file.uid"
        class="el-upload-list__item ele-upload-list__item-content"
        v-for="(file, index) in fileList"
      >
        <el-link :href="file.url" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script setup>
import { getToken } from '@/utils/auth'
import axios from 'axios'
import SparkMD5 from 'spark-md5'

const BaseApi = `${import.meta.env.VITE_APP_BASE_API}`
const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 1
  },
  // 大小限制(MB)
  // fileSize: {
  //   type: Number,
  //   default: 5
  // },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => []
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  //上传类型  1-图片，2-视频,3-apk
  uploadType: {
    type: String,
    default: '3'
  }
})

const { proxy } = getCurrentInstance()
const emit = defineEmits(['update:modelValue'])
const autoUpload = ref(true)
const number = ref(0)
const uploadList = ref([])
const uploadFileUrl = ref(
  `${import.meta.env.VITE_APP_BASE_API}${import.meta.env.VITE_GLOB_UPLOAD_BYTYPE_URL}`
) // 上传文件服务器地址
const headers = ref({
  'Content-Type': 'multipart/form-data',
  Authorization: 'Bearer ' + getToken()
})
const fileList = ref([])
const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize))

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      let temp = 1
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : props.modelValue.split(',')
      // 然后将数组转为对象数组
      fileList.value = list.map((item) => {
        if (typeof item === 'string') {
          item = { name: item.name ? item.name : item, url: item, id: item.id }
        }
        item.uid = item.uid || new Date().getTime() + temp++
        return item
      })
    } else {
      fileList.value = []
      return []
    }
  },
  { deep: true, immediate: true }
)

// 上传前校检格式和大小
const splitSize = 10 * 1024 * 1024
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split('.')
    const fileExt = fileName[fileName.length - 1]
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`)
      return false
    }
  }
  // 校检文件大小
  if (file.size > splitSize) {
    autoUpload.value = false
    proxy.$modal.msgError(
      `上传文件大小超过 ${splitSize / 1024 / 1024}MB将进行大文件分片上传，请稍后!`
    )
  }

  proxy.$modal.loading('正在上传文件，请稍候...')
  number.value++
  return true
}

const state = reactive({
  requestCancelQueue: [], // 请求方法队列（调用取消上传
  //上传进度
  progress: 0,
  showProgress: false,
  // 每上传一块的进度
  eachProgress: 0,
  // 总共有多少块。断点续传使用
  chunksKeep: 0,
  // 切割后的文件数组
  fileChunksKeep: [],
  // 这个文件，断点续传
  fileKeep: null,
  // 断点续传，文件md5
  fileMd5Keep: ''
})
// 大文件分块上传
function splitUpload(file, onProgress) {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    try {
      const chunks = Math.ceil(file.size / splitSize)
      state.chunksKeep = chunks
      const fileChunks = await splitFile(file, splitSize, chunks)
      state.fileChunksKeep = fileChunks
      console.log('fileChunks,文件数组切割后')
      console.log(fileChunks)
      //判断每上传一个文件，进度条涨多少,保留两位小数
      state.eachProgress = parseInt(Math.floor((100 / chunks) * 100) / 100)
      state.showProgress = true
      let currentChunk = 0

      for (let i = 0; i < fileChunks.length; i++) {
        // 服务端检测已经上传到第currentChunk块了，那就直接跳到第currentChunk块，实现断点续传
        console.log(currentChunk, i)
        // 此时需要判断进度条
        if (Number(currentChunk) === i) {
          // 每块上传完后则返回需要提交的下一块的index
          await postFile(
            {
              chunked: true,
              chunk: i,
              chunks,
              splitSize,
              fileName: file.name,
              fullSize: file.size,
              uid: file.uid,
              file: fileChunks[i]
            },
            onProgress
          )
          currentChunk++

          // 上传完一块后，进度条增加
          state.progress += state.eachProgress
          // 不能超过100
          state.progress = state.progress > 100 ? 100 : state.progress
        }
      }

      const spark = new SparkMD5.ArrayBuffer()
      let currentChunkMd5 = 0

      const reader = new FileReader()
      reader.onload = async function (e) {
        spark.append(e.target.result)
        currentChunkMd5++

        if (currentChunkMd5 < chunks) {
          loadNext(reader, currentChunkMd5, file)
        } else {
          // console.log(spark.end());
          var hashMd5111 = spark.end()
          state.fileMd5Keep = hashMd5111
          console.log(hashMd5111)
          // 在这里请求接口
          // await that.validateFile({
          //   name: file.name,
          //   uid: file.uid,
          //   md5: hashMd5111,
          //   chunks: fileChunks.length,
          //   filter_type: 'git_secret_file'
          //   // chunk: fileChunks.length,
          // })
        }
      }

      proxy.$modal.msgInfo('正在进行文件加密校验')

      await loadNext(reader, currentChunkMd5, file)
      // let hashMd5 = "";
      // // console.log(hashMd5)
      // console.log("进入分片上传的getHash");
      // function getHash(cb) {
      //   reader.onload = function(e) {
      //     console.log("进入分片上传的getHash的函数");
      //     const hash = SparkMD5.ArrayBuffer.hash(e.target.result);
      //     // const hash = SparkMD5.ArrayBuffer.hash(file);
      //     console.log(hash);
      //     that.hashMd5 = hash;
      //     console.log(that.hashMd5);
      //     that.fileMd5Keep = hash;
      //     cb(hash);
      //   };
      //   reader.readAsArrayBuffer(file);
      // }
      // await getHash(function() {
      //   console.log(that);
      //   that.validateFile({
      //     name: file.name,
      //     uid: file.uid,
      //     md5: that.hashMd5,
      //     chunks: fileChunks.length
      //     // chunk: fileChunks.length,
      //   });
      // });
      // 请求接口

      // console.log('fileChunks.length')
      // 请求接口
      //validateFile({
      //   fileName: file.name,
      //   uid: file.uid,
      //   md5:md5,
      //   chunks:1
      // });
      resolve()
    } catch (error) {
      reject(error)
    }
  })
}

async function loadNext(reader, currentChunkMd5, file) {
  const start = currentChunkMd5 * splitSize
  const end = start + splitSize >= file.size ? file.size : start + splitSize
  await reader.readAsArrayBuffer(file.slice(start, end))
}

// 文件分块,利用Array.prototype.slice方法
function splitFile(file, splitSize, chunks) {
  return new Promise((resolve, reject) => {
    try {
      setTimeout(() => {
        const fileChunk = []
        for (let chunk = 0; chunks > 0; chunks--) {
          fileChunk.push(file.slice(chunk, chunk + splitSize))
          chunk += splitSize
        }
        resolve(fileChunk)
      }, 0)
    } catch (e) {
      console.error(e)
      reject(new Error('文件切块发生错误'))
    }
  })
}

// 提交文件方法,将参数转换为FormData, 然后通过axios发起请求
function postFile(param, onProgress) {
  // console.log(param);
  const formData = new FormData()
  for (let p in param) {
    formData.append(p, param[p])
  }

  const config = {
    headers: headers.value,
    cancelToken: new axios.CancelToken(function executor(cancel) {
      if (state.requestCancelQueue[param.uid]) {
        state.requestCancelQueue[param.uid]()
        delete state.requestCancelQueue[param.uid]
      }
      state.requestCancelQueue[param.uid] = cancel
    }),
    onUploadProgress: (e) => {
      if (param.chunked) {
        e.percent = Number(
          (((param.chunk * (param.eachSize - 1) + e.loaded) / param.fullSize) * 100).toFixed(2)
        )
      } else {
        e.percent = Number(((e.loaded / e.total) * 100).toFixed(2))
      }
      onProgress(e)
    }
  }
  return axios.post(`${BaseApi}/api/file/partUpload`, formData, config).then((rs) => rs.data)
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`)
}

// 上传失败
function handleUploadError(err) {
  number.value--
  proxy.$modal.closeLoading()
  proxy.$modal.msgError(`上传文件失败:${err}`)
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    uploadList.value.push({
      name: res.data.name,
      url: res.data.url,
      resourceId: res.data.resourceId,
      resourceType: res.data.resourceType,
      size: res.data.size
    })
    uploadedSuccessfully()
  } else {
    number.value--
    proxy.$modal.closeLoading()
    proxy.$modal.msgError(res.msg)
    proxy.$refs.fileUpload.handleRemove(file)
    uploadedSuccessfully()
  }
}

// 删除文件
function handleDelete(index) {
  fileList.value.splice(index, 1)
  // emit('update:modelValue', listToString(fileList.value))
  emit('update:modelValue', fileList.value)
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.filter((f) => f.url !== undefined).concat(uploadList.value)
    uploadList.value = []
    number.value = 0
    emit('update:modelValue', fileList.value)
    // emit('update:modelValue', listToString(fileList.value))
    proxy.$modal.closeLoading()
  }
}

// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf('/') > -1) {
    return name.slice(name.lastIndexOf('/') + 1)
  } else {
    return name
  }
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = ''
  separator = separator || ','
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url + separator
    }
  }
  return strs != '' ? strs.substr(0, strs.length - 1) : ''
}
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
